var express = require('express'),
    bodyParser = require('body-parser'),
    rq = require("request"),
    async = require("async"),
    util = require("util");

var app = express();

app.use(bodyParser.urlencoded({extended: true}));

app.use(bodyParser.json());

app.get("/service", function (req, res) {

    // 先判断session, 有session从中取得access_token以及access_token过期时间
    // 如果缓存过用户数据同时取得用户数据(设置一个更新时间,比access_token过期时间短一些,不必每次都去取数据)
    // 数据过期 -> 用access_token取
    // access_token过期 -> 用refresh_token获取access_token -> 再去用access_token取
    // refresh_token过期 -> 跳转再次授权

    var code = req.query.code, url;
    if (!code) {
        url = util.format("http://localhost:3000/oauth/authorise?client_id=%s&redirect_uri=%s", "plane", "http://localhost:3001/service");
        return res.redirect(url);
    }

    async.waterfall([
        (next) => {
            var form = {
                "client_id": "plane",
                "client_secret": "THISisAUTO-generatedSECRET",
                "grant_type": "authorization_code",
                "code": code
            };
            rq.post("http://localhost:3000/oauth/token", {"form": form}, (err, res, body) => {
                // 这一步的 access_token 应该缓存起来, 留作过期时间内再次使用
                console.log("Get OAuth Token: ", body);
                let data = JSON.parse(body);
                let access_token = data.access_token;
                next(err, access_token);
            });
        },
        (access_token, next) => {
            rq.post("http://localhost:3000/secret", {"form": {"access_token": access_token}}, (err, res, body) => {
                // 这一步的数据应该缓存起来, 留作过期时间内再次使用
                console.log("Get Data With Auth [ %s ]", body);
                next(err, body);
            });
        }
    ], (err, body) => {
        console.log("Auth Info [ %s ]", body);
        console.log("获取到授权信息, 开始执行真正逻辑...");
        res.end();
    });
});

app.listen(3001, () => {
    console.log("Listen On Port [ %s ]", 3001);
});



